import { useCallback, useEffect, useMemo, useState, useRef } from 'react'
import style from './index.module.less'
import { getCaseList } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { Button, InfiniteScroll, PullToRefresh, Space, SpinLoading, Picker } from 'antd-mobile'
import { SearchOutline, AddOutline, DownOutline } from 'antd-mobile-icons'
import Item from './components/item'
import PageEmpty from '@components/pageEmpty'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { push } from '@src/redux/reducers/pages'
import { refreshCaseListVersion } from '@src/redux/reducers/cases'

const maxX = window.document.documentElement.offsetWidth - 60
const maxY = window.document.documentElement.offsetHeight - 164

const types = ['全部', '未提交', '待审核', '已受理', '送达中', '审理中', '已结案', '已归档', '不予受理', '审核不通过']
async function getList (list, current, caseno, type, setList, setTotal, setLoading) {
  if (list.length === 0) {
    setList([])
  }
  const condition = getCondition(caseno)
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseList(current, condition, type))
  setLoading(false)
  if (e === null && d !== null) {
    setList([...list, ...d.list])
    setTotal(d.total)
  }
}

async function loadMoreFn (list, current, caseno, type, setList, setTotal, setLoading) {
  if (list.length === 0) {
    setList([])
  }
  const condition = getCondition(caseno)
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseList(current, condition, type))
  setLoading(false)
  if (e !== null) {
    throw new Error(e.message)
  }
  if (e === null && d !== null) {
    setList([...list, ...d.list])
    setTotal(d.total)
  }
}

function getCondition (caseno) {
  const condition = []
  if (typeof caseno === 'string' && caseno !== '') {
    condition.push({ k: 'c.caseno_desc', o: 'like', v: `%${caseno}%` })
  }
  return condition
}

function Main () {
  const btnRef = useRef()
  const dispatch = useAppDispatch()
  const caseListVersion = useAppSelector(state => state.cases.caseListVersion)
  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const [caseno, setCaseno] = useState('')
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(true)
  const [type, setType] = useState(types[0])
  const [typeVisible, setTypeVisible] = useState(false)
  const [x, setX] = useState(window.document.documentElement.offsetWidth - 80)
  const [y, setY] = useState(window.document.documentElement.offsetHeight - 200)
  const [cx, setCx] = useState(0)
  const [cy, setCy] = useState(0)
  const [moving, setMoving] = useState(false)
  const hasMore = useMemo(() => {
    return list.length < total
  }, [total, list])
  const loadMore = useCallback(async () => {
    await loadMoreFn(list, list.length / 10 + 1, caseno, type, setList, setTotal, setLoading)
  }, [caseno, list, type])
  useEffect(() => {
    getList([], 1, caseno, type, setList, setTotal, setLoading)
  }, [caseno, caseListVersion, type])
  return (
    <div className={style.container}>
      <Picker
        columns={[types]}
        visible={typeVisible}
        onClose={() => {
          setTypeVisible(false)
        }}
        value={[type]}
        onConfirm={v => {
          setType(v[0])
        }}
      />
      <div className={style.header}>
        <div className={style.toggle}>
          <Button size='small' className={style.type} onClick={() => setTypeVisible(true)}>
            <Space>
              <span>{type}</span>
              <DownOutline />
            </Space>
          </Button>
        </div>
        <div className={style.search}>
          <div className={style['search-icon']}><SearchOutline /></div>
          <input placeholder='请输入案号' value={search} onInput={e => { setSearch(e.target.value) }} />
          <button className={style['search-btn']} onClick={() => { setCaseno(search); dispatch(refreshCaseListVersion()) }}>搜索</button>
        </div>
      </div>
      <div
        className={style.body}
        onTouchMove={e => {
          if (!moving) {
            return undefined
          }
          const o = e.changedTouches[0]
          const nx = o.clientX + cx
          const ny = o.clientY + cy
          const rx = nx > maxX ? maxX : nx < 0 ? 0 : nx
          const ry = ny > maxY ? maxY : ny < 0 ? 0 : ny
          // btnRef.current.setAttribute('style', `left:${rx}px;top:${ry}px`)
          setX(rx)
          setY(ry)
        }}
        onTouchEnd={() => {
          setMoving(false)
        }}
      >
        <div className={style.inner}>
          <PullToRefresh
            onRefresh={async () => {
              await loadMoreFn([], 1, caseno, type, setList, setTotal, setLoading)
            }}>
            <div>
              {loading && list.length === 0 && (
                <div className={style.loading}>
                  <SpinLoading />
                </div>
              )}
              {
                !loading && list.length === 0 && (
                  <PageEmpty />
                )
              }
              <div className={style.list}>
                {
                  list.map((li) => {
                    return <Item key={li.id} data={li} />
                  })
                }
              </div>
              {
                list.length > 0 && <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
              }
            </div>
          </PullToRefresh>
        </div>
        <button
          ref={btnRef}
          className={style.add}
          style={{ left: `${x}px`, top: `${y}px` }}
          onTouchStart={e => {
            setMoving(true)
            const o = e.changedTouches[0]
            setCy(btnRef.current.offsetTop - o.clientY)
            setCx(btnRef.current.offsetLeft - o.clientX)
          }}
          onClick={() => {
            dispatch(push({ element: 'addCaseProtocol' }))
          }}
        >
          <span><AddOutline /></span>
        </button>
      </div>
    </div>
  )
}

export default Main
